# encoding: utf-8
# @File  : docker_client.py
# @Author: shaoyun
# @Date  :  2025/05/11
import logging
from typing import Optional

import docker
from docker.client import DockerClient as Client

from app.core.config import settings

logger = logging.getLogger(__name__)


class DockerClient:
    """Docker客户端单例"""

    _client: Optional[Client] = None

    @classmethod
    def get_client(cls) -> Client:
        """获取Docker客户端单例"""
        if cls._client is None:
            try:
                cls._client = docker.from_env()
                logger.info("Docker client initialized")

                # 确保网络存在
                cls._ensure_network()
            except Exception as e:
                logger.error(f"Failed to initialize Docker client: {e}")
                raise

        return cls._client

    @classmethod
    def _ensure_network(cls) -> None:
        """确保Docker网络存在"""
        try:
            networks = cls._client.networks.list(names=[settings.DOCKER_NETWORK])
            if not networks:
                logger.info(f"Creating Docker network: {settings.DOCKER_NETWORK}")
                cls._client.networks.create(
                    name=settings.DOCKER_NETWORK,
                    driver="bridge"
                )
            else:
                logger.info(f"Docker network already exists: {settings.DOCKER_NETWORK}")
        except Exception as e:
            logger.error(f"Failed to ensure Docker network: {e}")
            raise

    @classmethod
    def close(cls) -> None:
        """关闭Docker客户端"""
        if cls._client:
            cls._client.close()
            cls._client = None
            logger.info("Docker client closed")